package com.dwjm.shop.goods;

import com.dwjm.shop.merchant.MerchantDao;
import com.dwjm.shop.merchant.MerchantDaoImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

@WebServlet(name = "GoodsController", urlPatterns = {"/addgoods", "/deletegoods"})
public class GoodsController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        try {
            String title = req.getParameter("title");
            String price = req.getParameter("price");
            String description = req.getParameter("description");
            String img = req.getParameter("img");
            String mid = req.getParameter("mid");

            Goods goods = new Goods(null, title, new BigDecimal(price), description, img, 0, Integer.parseInt(mid));
            GoodDao merchantDao = new GoodDaoImpl();
            int i = merchantDao.addGoods(goods);
            if (1 == i) {
                resp.getWriter().write("y");
            } else {
                resp.getWriter().write("N");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"error\":\"" + (e.getMessage() == null ? "未知错误" : e.getMessage().replace("\"", "\\\"")) + "\"}");
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        try {
            String idStr = req.getParameter("id");
            if (idStr == null) {
                resp.getWriter().write("{\"error\":\"缺少商品ID\"}");
                return;
            }
            int id = Integer.parseInt(idStr);
            GoodDao goodDao = new GoodDaoImpl();
            int result = goodDao.deleteGoods(id);
            if (result == 1) {
                resp.getWriter().write("{\"success\":true}");
            } else {
                resp.getWriter().write("{\"success\":false,\"msg\":\"删除失败\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("{\"error\":\"" + (e.getMessage() == null ? "未知错误" : e.getMessage().replace("\"", "\\\"")) + "\"}");
        }
    }
}
